package com.freely.ui.activities;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.request.RequestOptions;
import com.freely.R;
import com.freely.R2;
import com.freely.component.BaseRecyclerViewAdapter;
import com.freely.component.activity.NavigationActivity;
import com.freely.data.database.FreelyDatabase;
import com.freely.data.entities.Group;
import com.freely.data.managerUtils.FreelySharedPreferences;
import com.freely.data.network.requestEntities.RQUserId;
import com.freely.data.repository.entities.GroupChatMessage;
import com.freely.data.rxBus.RxBus;
import com.freely.data.services.FreelyServiceKt;
import com.freely.ui.util.DateFormat;
import com.freely.ui.util.ErrorUtil;
import com.freely.ui.viewModel.HomeViewModel;
import com.google.android.material.bottomsheet.BottomSheetDialog;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.Single;
import io.reactivex.SingleOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okio.ByteString;

public class HomeActivity extends NavigationActivity {
    private static final String TAG = "HomeActivity";
	public static final String NEW_GROUP = "new_group";
	public static final String ACTION = "action";
	public static final String GROUP_CHANGE = "change";
	public static final String GROUP_REMOVE = "remove";
    private static final int REQUEST_CODE_MESSAGE = 1;
    @BindView(R2.id.search_group)
    TextView searchGroup;
    @BindView(R2.id.recycler_view)
    RecyclerView recyclerView;

    private HomeViewModel viewModel;
    private BaseRecyclerViewAdapter adapter;
    private View.OnClickListener startMessageActivity = v -> {
        MessageActivity.startActivity(
                HomeActivity.this,
                REQUEST_CODE_MESSAGE,
                FreelySharedPreferences.getInstance().getUserId()
        );
    };

	public static void startActivity(@NonNull Context context) {
		Intent intent = new Intent(context, HomeActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
		context.startActivity(intent);
    }

	@Override
	protected void onStart() {
		super.onStart();
		Log.d(TAG, "onStart: ");
	}

	//已加入群列表item点击事件
    private void RVItemOnClick(long groupId) {
        GroupChatActivity.startActivity(this, groupId);
    }

    //创建toolbar
    @Override
    protected void onCreateToolbar(Toolbar toolbar, TextView title, ImageButton logo) {
        super.onCreateToolbar(toolbar, title, logo);
        title.setOnClickListener(view -> {
			BottomSheetDialog dialog = new BottomSheetDialog(this);
			dialog.setContentView(R.layout.dialog_map);
			dialog.getDelegate().findViewById(R.id.design_bottom_sheet)
                    .setBackgroundColor(getResources().getColor(android.R.color.transparent));
			dialog.show();
		});
        toolbar.setNavigationIcon(null);
        setLogoEnable(true);
        logo.setPadding(0,5,0,5);
        logo.setOnClickListener(v -> {
            DetailActivity.startActivity(this);
        });
        Glide.with(this)
                .load(R.drawable.user_white)
                .apply(RequestOptions.circleCropTransform())
                .into(logo);
        toolbar.inflateMenu(R.menu.main_menu);
        toolbar.setOnMenuItemClickListener(item -> {
            boolean result = false;
            switch (item.getItemId()){
                case R.id.toolbar_create_group:
                    CreateGroupActivity.startActivity(HomeActivity.this);
                    result = true;
                    break;
                case R.id.toolbar_join_group:
                    GroupJoinActivity.startActivity(this);
                    result = true;
                    break;
            }
            return result;
        });
    }

    private void init(){
        //viewModel 初始化
        viewModel = ViewModelProviders.of(this).get(HomeViewModel.class);

        //加载头像完成回调
        viewModel.getHeadIcon().observe(this,bytes -> {
            Glide.with(this)
                    .asBitmap()
                    .load(bytes)
                    .apply(RequestOptions.circleCropTransform())
                    .into(getLogo());
        });

        //获取已加入群列表
        viewModel.getGroupList().observe(this,groups -> {
            adapter.notifyDataSetChanged();
        });

        //recyclerView 关闭滑动
        recyclerView.setNestedScrollingEnabled(false);
        //recyclerView 设置布局管理器
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        // recyclerAdapter
        adapter = new BaseRecyclerViewAdapter() {
            @Override
            public int getItemCount() {
                return viewModel.getGroupList().getValue().size() + 1;
            }
        };
        adapter.getView(position -> {
            if (position == 0) {
                return R.layout.item_message;
            } else {
                return R.layout.activity_home_recycler_item;
            }
        });
        adapter.onBindView((holder, position) -> {
            Log.d(TAG, "init: position = " + position);
            ImageView headIcon = holder.getView(R.id.head_icon);
            TextView title = holder.getView(R.id.title);
            TextView content = holder.getView(R.id.content);
            TextView time = holder.getView(R.id.time);

            if (position == 0) {
                holder.itemView.setOnClickListener(startMessageActivity);
                return;
            }

            //获得群item
            Log.d(TAG, "init: ----------开始显示群列表----------");
            Group group = viewModel.getGroupList().getValue().get(position - 1);
            Log.d(TAG, "init: group=" + group.toString());

            //解码头像显示
            Log.d(TAG, "init: 解码显示头像");
            Disposable disposable = Single.create((SingleOnSubscribe<RequestBuilder<Drawable>>)
                    emitter -> {
                        RequestBuilder<Drawable> builder = Glide.with(HomeActivity.this)
                                .load(ByteString.decodeBase64(group.getGroupImage()).toByteArray())
                                .apply(RequestOptions.circleCropTransform());
                        emitter.onSuccess(builder);
                    }).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(builder -> builder.into(headIcon),ErrorUtil::errorHint);
            register(disposable);
            //设置群名
            Log.d(TAG, "init: 设置群名");
            Log.d(TAG, "id "+group.getGroupAdmin());
            title.setText(group.getGroupName());
            //查询最新的聊天消息
            Log.d(TAG, "init: 查询聊天消息");
            Single<GroupChatMessage> maybe = FreelyDatabase.getInstance()
                    .chatRecordDAO()
                    .getNewGroupChatMessage(group.getGroupId());
            Disposable maybeDisposable = maybe.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(groupChatMessage -> {
                        //设置聊天消息
                        Log.d(TAG, "init: 设置聊天消息内容");
                        content.setText(groupChatMessage.getMessage());
                        //设置最新聊天消息发送时间
                        Log.d(TAG, "init: 设置聊天消息发送时间");
                        time.setText(DateFormat.format(DateFormat.TIME_FORMAT,groupChatMessage.getTime()));
                    },throwable -> {
                        Log.d(TAG, "init: 没有聊天消息");
                        content.setText(null);
                        time.setText(null);
                    });
            register(maybeDisposable);
            //设置群item监听器
            Log.d(TAG, "init: 设置群列表item监听");
                holder.itemView.setOnClickListener(v -> {
                    Log.d(TAG, "init: groupId=" + group.getGroupId());
                    HomeActivity.this.RVItemOnClick(group.getGroupId());
                });
        });
        recyclerView.setAdapter(adapter);

        //搜索监听
        searchGroup.setOnClickListener(v -> {
            SearchActivity.startActivity(this);
        });

        //加载头像
        viewModel.loadHeadIcon(FreelySharedPreferences.getInstance().getUserId());
        //加载已加入群列表
		viewModel.loadJoinedGroupListForInternet(new RQUserId(FreelySharedPreferences.getInstance().getUserId()));
    }

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);
		init();
		Disposable disposable = RxBus.Companion.getInstance()
				.toObservable(FreelyServiceKt.ADD_NEW_GROUP, Group.class)
				.observeOn(AndroidSchedulers.mainThread())
				.subscribe(group -> {
					Log.d(TAG, "onCreate: 更新列表");
					viewModel.getGroupList().getValue().add(0, group);
					adapter.notifyItemInserted(1);
				}, ErrorUtil::errorHint);
		register(disposable);
/*		Disposable messageDisposable = RxBus.Companion.getInstance()
				.toObservable(FreelyServiceKt.GROUP_CHAT_MESSAGE, ChatRecord.class)
				.subscribe(chatRecord -> {
					List<Group> list = viewModel.getGroupList().getValue();
					Observable.fromIterable(list)
							.observeOn(AndroidSchedulers.mainThread())
							.filter(new Predicate<Group>() {
								@Override
								public boolean test(Group group) throws Exception {
									return chatRecord.getGroupId() == group.getGroupId();
								}
							})
							.subscribe(group -> {
								int index = list.indexOf(group);

							})
							.dispose();
				});*/
//		register(messageDisposable);
    }

	public static void startActivity(@NonNull Context context, String action, long groupId) {
        Intent intent = new Intent(context, HomeActivity.class);
		switch (action) {
			case GROUP_CHANGE:
				intent.putExtra(GROUP_CHANGE, groupId);
				intent.putExtra(ACTION, GROUP_CHANGE);
				break;
			case GROUP_REMOVE:
				intent.putExtra(GROUP_REMOVE, groupId);
				intent.putExtra(ACTION, GROUP_REMOVE);
				break;
		}
        context.startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_CODE_MESSAGE:
                long[] groups = data.getLongArrayExtra(Group.group_id);
                if (groups == null || groups.length == 0) {
                    return;
                }
				viewModel.loadJoinedGroupListForInternet(new RQUserId(FreelySharedPreferences.getInstance().getUserId()));
                break;
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
		switch (intent.getStringExtra(ACTION)) {
			case GROUP_CHANGE:
				changeGroup(intent.getLongExtra(GROUP_CHANGE, -1));
				break;
			case GROUP_REMOVE:
				removeGroup(intent.getLongExtra(GROUP_REMOVE, -1));
				break;
		}

	}

	private void changeGroup(long groupId) {
		if (groupId == -1) {
			return;
		}

		Disposable disposable = FreelyDatabase.getInstance()
				.groupDAO()
				.getGroupByGroupId(groupId)
				.subscribeOn(Schedulers.io())
				.observeOn(AndroidSchedulers.mainThread())
				.subscribe(group -> {
					List<Group> list = viewModel.getGroupList().getValue();
					if (list != null) {
						list.size();
						list.add(list.size(), group);
                        adapter.notifyDataSetChanged();
					}
				}, ErrorUtil::errorHint);
		register(disposable);
	}

	private void removeGroup(long groupId) {
		if (groupId == -1) {
			return;
		}
		List<Group> list = viewModel.getGroupList().getValue();
		if (list == null || list.isEmpty()) {
			return;
		}
		Disposable disposable = Observable.fromIterable(list)
				.filter(group -> groupId == group.getGroupId())
				.subscribeOn(Schedulers.computation())
				.observeOn(AndroidSchedulers.mainThread())
				.subscribe(group -> {
					int index = list.indexOf(group);
					Log.e(TAG, "removeGroup: " + index);
					list.remove(index);
                    adapter.notifyDataSetChanged();
				}, ErrorUtil::errorHint);
		register(disposable);

	}

    @Override
    public void onBackPressed() {
        Intent home = new Intent(Intent.ACTION_MAIN);
        home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        home.addCategory(Intent.CATEGORY_HOME);
        startActivity(home);
    }

    @Override
    public void onResume() {
        super.onResume();
		if (viewModel == null)
			viewModel = ViewModelProviders.of(this).get(HomeViewModel.class);

		Log.e(TAG, "onResume: ");
		viewModel.loadHeadIcon(FreelySharedPreferences.getInstance().getUserId());
		viewModel.getHeadIcon().observe(this, bytes -> {
			Glide.with(this)
					.asBitmap()
					.load(bytes)
					.apply(RequestOptions.circleCropTransform())
					.into(getLogo());
		});
    }
}
